/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.easyedu.dictionary.explorer.nodes;

import eu.easyedu.dictionary.api.model.Dictionary;
import eu.easyedu.dictionary.api.util.DictionaryManager;
import eu.easyedu.dictionary.api.util.AbstractOpenDictionaryAction;
import java.awt.Image;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.swing.Action;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.nodes.Sheet;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.lookup.Lookups;

/**
 *
 * @author hlavki
 */
public class DictionaryNode extends AbstractNode {

    private static final String DICTIONARY_ICON_PATH = "eu/easyedu/dictionary/api/resources/dictionary16x16.png";
    private Dictionary dictionary;
    private Lookup actionsLookup = Lookups.forPath("Actions/Plugins/Dictionary/");
    private Action openAction = null;

    public DictionaryNode(Dictionary dictionary) {
        super(Children.LEAF, Lookups.singleton(dictionary));
        this.dictionary = dictionary;
        setDisplayName(dictionary.toString());
    }

    @Override
    public Image getIcon(int type) {
        return ImageUtilities.loadImage(DICTIONARY_ICON_PATH);
    }

    @Override
    protected Sheet createSheet() {
        return new DictionarySheet(dictionary).getSheet();
    }

    @Override
    public Action[] getActions(boolean context) {
        List<Action> actions = Arrays.asList(super.getActions(context));
        Collection<? extends Action> newActions = actionsLookup.lookupAll(Action.class);
        List<Action> result = new ArrayList<Action>(actions.size() + newActions.size());
        result.addAll(actions);
        result.addAll(newActions);
        return result.toArray(new Action[0]);
    }

    @Override
    public Action getPreferredAction() {
        return getOpenAction();
    }

    public synchronized Action getOpenAction() {
        if (openAction == null) {
            for (Action action : getActions(false)) {
                if (action instanceof AbstractOpenDictionaryAction) {
                    openAction = action;
                }
            }
        }
        return openAction;
    }

    @Override
    public String getHtmlDisplayName() {
        String result = null;
        if (dictionary.equals(DictionaryManager.getDefault().getDefaultDictionary())) {
            result = "<b>" + dictionary.toString() + "</b>";
        }
        return result;
    }

    public Node.Property<?>[] getProperties() {
        return dictionary.getNodeProperties();
    }

    @Override
    public Node.PropertySet[] getPropertySets() {
        Sheet.Set props = new Sheet.Set();
        props.setName("Basic Properties");
        props.put(getProperties());
        return new Node.PropertySet[]{props};
    }
}
